package com.cykj.page03;


import com.cykj.page03.servlet.LoginServlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;


/**
 * @BelongsProject: HandTomcat
 * @BelongsPackage: com.cykj.page02
 * @Author: WWJ
 * @CreateTime: 2025-06-18 10:17
 * @Description: 线程的任务对象
 * @Version: 1.0
 */
public class MyTask implements Runnable {

    private Socket socket;

    public MyTask(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            while (true) {
                InputStream inputStream = socket.getInputStream();
                byte[] bytes = new byte[1024];
                int len = inputStream.read(bytes);
                String request = new String(bytes, 0, len);
                System.out.println("客户端请求数据：\n" + request);
                //请求消息
                MyHttpRequest httpRequest = new MyHttpRequest(request);
                //把响应拿到外面，因为动态资源和静态资源都需要
                MyHttpResponse httpResponse = new MyHttpResponse(socket);
                if (httpRequest.getRequestModel().contains(".") || httpRequest.getRequestModel().equals("/")) {
                    //静态资源
                    System.out.println("我进来静态资源");
                    String filePath = "webapps" + httpRequest.getRequestURL();

                    File file = new File(filePath);
                    if (!file.exists()) {
                        filePath = "webapps/pages/404.html";
                    }
                    if (httpRequest.getRequestURL().equals("/")) {
                        filePath = "webapps/pages/index.html";
                    }
                    //静态资源处理器
                    StaticResourceHandler staticResourceHandler = new StaticResourceHandler(filePath);
                    httpResponse.write(staticResourceHandler.getMedia(), staticResourceHandler.getFileBytes());
                } else {
                    //动态资源
                    switch (httpRequest.getRequestModel()) {
                        case "/login":
                            System.out.println("我进来登录了");
                            new LoginServlet().handlerServlet(httpRequest, httpResponse);
                            break;
                        case "/enroll":
//                            new EnrollServlet().handlerServlet(httpRequest, httpResponse);
                            break;
                        case "/getUser":
                            System.out.println("获取用户信息");
                            break;
                        case "/updatePwd":
                            System.out.println("修改密码");
                            break;
                        default:
                            //404
                            break;
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
